<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Listener;

use App\Lib\Consul\Agent;
use App\Lib\Consul\ServiceConfig;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Bean\BeanFactory;
use Swoft\Consul\Exception\ClientException;
use Swoft\Consul\Exception\ServerException;
use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Http\Server\HttpServer;
use Swoft\Log\Helper\CLog;
use Swoft\Server\SwooleEvent;

/**
 * Class DeregisterServiceListener
 *
 * @since 2.0
 *
 * @Listener(SwooleEvent::SHUTDOWN)
 */
class DeregisterServiceListener implements EventHandlerInterface
{
    /**
     * @Inject()
     *
     * @var Agent
     */
    private $agent;

    /**
     * @param EventInterface $event
     */
    public function handle(EventInterface $event): void
    {
        if(env('APP_ENV', 'local') === 'local') {
            /** @var HttpServer $httpServer */
            $httpServer = $event->getTarget();
            /** @var ServiceConfig $ServiceConfig */
            $ServiceConfig = BeanFactory::getBean("ServiceConfig");
            try {
                $this->agent->deregisterService($ServiceConfig->getUuid());


                $this->agent->deregisterService('2B11445E-68C3-8B5A-7CA9-7105D36EB1B0');
                $this->agent->deregisterService('87FF188F-3E87-CDF1-AC86-47262CE7CEC1');
                $this->agent->deregisterService('8952C105-CB04-5F51-2171-4848607322D2');
                $this->agent->deregisterService('AE268BD6-0E6C-7190-D9DF-E7FD01F7F281');
            } catch (ClientException $e) {
                // consul 请求异常 链接成功但是请求参数或者请求格式错误
                CLog::error('consul 请求异常 链接成功但是请求参数或者请求格式错误！');
                return;
            } catch (ServerException $e) {
                // consul IP地址链接不到
                CLog::error('consul IP地址或端口错误，链接不到服务！');
                return;
            }
        }
    }
}
